package com.youan.log.common.threadtask;

import com.youan.log.common.entity.ThreadTaskProgress;
import com.youan.log.common.service.IThreadTaskProgressService;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.Validate;
import org.springblade.core.tool.utils.SpringUtil;

/**
 * 任务进度的进步器
 */
public class ThreadTaskProgressor {

    private IThreadTaskProgressService taskProgressService;

    /**
     * 多少个进度一提交
     */
    @Setter
    private int progressCommitSize = 10;
    /**
     * 当前进度
     */
    @Getter
    private int progressCurrentNum = 0;
    /**
     * 总进度
     */
    @Getter
    private int progressTotalNum = 0;

    @Getter
    private Long progressId;

    public ThreadTaskProgressor(Long progressId) {
        this.progressId = progressId;
        this.taskProgressService = SpringUtil.getBean(IThreadTaskProgressService.class);
        Validate.notNull(taskProgressService, "TaskThreadProgressor必须在Spring环境下使用，并且容器中存在[IThreadTaskLogService]类型的实例");
    }

    public void addProgressNum(){
        this.addProgressNum(1);
    }

    public void addProgressNum(int num){
        if(this.progressTotalNum == 0) return;
        this.progressCurrentNum += num;
        if(this.progressCurrentNum % progressCommitSize == 0) {
            doAddProgressNum();
        }
        if(this.progressCurrentNum == this.progressTotalNum) {
            doAddProgressNum();
        }
    }

    /**
     * 追加任务总数
     * @author xsh
     * @date 2021/3/19 16:05
     * @param: progressTotal
     * @return
     */
    public void updateProgressTotal(Integer progressTotal) {
        this.progressTotalNum = progressTotal;

        ThreadTaskProgress progress = new ThreadTaskProgress();
        progress.setId(this.progressId);
        progress.setTaskProgressTotal(progressTotal);
        this.taskProgressService.updateById(progress);
    }

    /**
     * 重置任务总数
     * @author xsh
     * @date 2021/3/19 16:05
     * @param: progressTotal
     * @return
     */
    public void resetProgressTotal(Integer progressTotal) {
        this.progressTotalNum = progressTotal;
        this.progressCurrentNum = 0;

        ThreadTaskProgress progress = new ThreadTaskProgress();
        progress.setId(this.progressId);
        progress.setTaskProgressTotal(progressTotal);
        progress.setTaskProgressCurrent(0);
        this.taskProgressService.updateById(progress);
    }

    private void doAddProgressNum( ) {
        ThreadTaskProgress progress = new ThreadTaskProgress();
        progress.setId(this.progressId);
        progress.setTaskProgressCurrent(this.progressCurrentNum);
        this.taskProgressService.updateById(progress);
    }

    public boolean taskIsEnd() {
        return this.progressTotalNum == this.progressCurrentNum;
    }




}
